package com.yt.sys.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.yt.sys.models.vo.SysRolePermissionVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.sys.mapper.SysRolePermissionMapper;
import com.yt.sys.models.service.ISysRolePermissionService;
import com.yt.sys.models.bo.SysRolePermissionSaveBO;
import com.yt.sys.models.dto.SysRolePermissionDTO;
import com.yt.common.exception.BusinessException;
import com.yt.common.enums.CodeEnum;
import com.yt.product.common.config.YmlConfig;
import org.springframework.beans.factory.annotation.Autowired;

@DubboService
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermissionDTO> implements ISysRolePermissionService{

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public boolean add(SysRolePermissionSaveBO saveBO) {
        // 1. 参数校验
        validateRolePermissionSaveBO(saveBO);

        // 2. BO转换为DTO
        SysRolePermissionDTO dto = new SysRolePermissionDTO();
        BeanUtils.copyProperties(saveBO, dto);

        // 3. 设置默认值
        setRolePermissionDefaultValues(dto);

        // 4. 生成并设置主键ID
        Long id = ymlConfig.getPkId();
        dto.setId(id);

        // 5. 插入数据库
        return this.insert(dto);
    }

    /**
     * 角色权限关联参数校验
     */
    private void validateRolePermissionSaveBO(SysRolePermissionSaveBO saveBO) {
        if (saveBO == null) {
            throw new BusinessException(CodeEnum.FAIL_100001.getCode(), "关联信息不能为空");
        }
        if (saveBO.getRoleId() == null) {
            throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "角色ID不能为空");
        }
        if (saveBO.getPermissionId() == null) {
            throw new BusinessException(CodeEnum.FAIL_100003.getCode(), "权限ID不能为空");
        }
    }

    /**
     * 设置角色权限关联默认值
     */
    private void setRolePermissionDefaultValues(SysRolePermissionDTO dto) {
        // 乐观锁版本号默认0
        dto.setRevision(dto.getRevision() != null ? dto.getRevision() : 0);

        // 创建时间和更新时间默认当前时间
        Date now = new Date();
        dto.setCreateTime(dto.getCreateTime() != null ? dto.getCreateTime() : now);
        dto.setUpdateTime(dto.getUpdateTime() != null ? dto.getUpdateTime() : now);
    }

    @Override
    public Page<SysRolePermissionVO> selectRolePermissionPage(
            Page<SysRolePermissionVO> page,
            Map<String, Object> params) {

        List<SysRolePermissionVO> records = sysRolePermissionMapper.selectRolePermissionPage(page, params);

        return page.setRecords(records);
    }
}